package org.example;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class demo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /*反射获取构造方法*/
        //获取字节码文件
        Class aClass = Class.forName("org.example.Student");

        //获取构造方法，不包括私有的
        Constructor[] cons = aClass.getConstructors();
        for (Constructor con:cons){
            System.out.println(con);
//            public org.example.Student()
//public org.example.Student(java.lang.String)
        }

        //获取所有构造方法
        Constructor[] cons1 = aClass.getDeclaredConstructors();
        for (Constructor con : cons1){
            System.out.println(con);
// private org.example.Student(java.lang.String,int)
//public org.example.Student(java.lang.String)
//public org.example.Student()
        }


//        获取单个构造方法
        Constructor con4 = aClass.getDeclaredConstructor(String.class,int.class);

        //获取权限修饰符
        int modifiers = con4.getModifiers();
        System.out.println(modifiers);

        //获取参数
        Parameter[] parameters = con4.getParameters();
        for (Parameter parameter : parameters){
            System.out.println(parameter);
        }
        //暴力反射：表示临时取消权限校验
        con4.setAccessible(true);
        Student stu = (Student) con4.newInstance("张三",23);

        System.out.println(stu);
    }
}
